package edu.neu.swc.skynet.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * <h1>事件推送</h1>
 * Aware: 动态更新路由网关 Service
 * 该方式为代码实现监听
 * 也可以通过配置文件实现监听
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class DynamicRouteServiceImpl implements
        ApplicationEventPublisherAware {

    /** 写路由定义 */
    private final RouteDefinitionWriter routeDefinitionWriter;

    /** 获取路由定义 */
    private final RouteDefinitionLocator routeDefinitionLocator;

    /** 事件发布 */
    private ApplicationEventPublisher publisher;

    public DynamicRouteServiceImpl(RouteDefinitionWriter routeDefinitionWriter,
                                   RouteDefinitionLocator routeDefinitionLocator){
        this.routeDefinitionWriter = routeDefinitionWriter;
        this.routeDefinitionLocator = routeDefinitionLocator;
    }

    @Override
    public void setApplicationEventPublisher(
            ApplicationEventPublisher applicationEventPublisher) {
        //完成事件推送句柄初始化
        this.publisher = applicationEventPublisher;
    }

    /**
     * <h2>增加路由定义</h2>
     * @param definition 路由定义对象
     * @return String 字符串
     */
    public String addRouteDefinition(RouteDefinition definition){

        log.info("gateway add route:[{}]",definition);

        //保存路由并发布
        routeDefinitionWriter.save(Mono.just(definition)).subscribe();

        //发布事件通知给gateway，同步新增的路由定义
        this.publisher.publishEvent(new RefreshRoutesEvent(this));

        return "success";
    }

    /**
     * <h2>通过路由ID删除路由配置</h2>
     * @param id 传递的配置Id
     * @return 删除成功 "success" 删除失败 "delete fail"
     */
    private String deleteById(String id){
        try{
            log.info("gateway delete route id:[{}]",id);
            this.routeDefinitionWriter.delete(Mono.just(id)).subscribe();
            //发布事件通知，gateway更新路由定义
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            return "success";
        }catch(Exception ex){
            log.error("gateway delete route fail[{}]",ex.getMessage(),ex);
            return "delete fail";
        }
    }

    /**
     * <h2>更新路由</h2>
     * 实现策略较为简单，删除+新增 = 更新
     * @param routeDefinition 传递的更新路由的定义
     * @return 是否更新成功
     */
    private String updateByRouteDefination(RouteDefinition routeDefinition){
        try {
            log.info("gateway update route:[{}]", routeDefinition);
            this.routeDefinitionWriter.delete(Mono.just(routeDefinition.getId()));

        }catch (Exception ex){
            return "update fail, not find route routeId:" + routeDefinition;
        }

        try{
            routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe();
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            return "success";
        }catch(Exception ex){
            return "update route fail";
        }
    }

    /**
     * <h2>更新路由</h2>
     * 以列表的形式更新路由信息
     * @param definitions 更新的路由定义
     * @return String 是否批量更新成功
     */
    public String updateList(List<RouteDefinition> definitions){
        log.info("getaway update route:[{}]", definitions);
        //先拿到当前geteway中存储的路由定义
        List<RouteDefinition> routeDefinitionExits =
                routeDefinitionLocator.getRouteDefinitions().buffer().blockFirst();
        if(!CollectionUtils.isEmpty(routeDefinitionExits)){
            //清除掉所有的旧的路由定义
            routeDefinitionExits.forEach(rd -> {
                log.info("delete route definition:[{}]", rd);
                deleteById(rd.getId());
            });
        }

        //把更新的路由定义同步到gateway中
        definitions.forEach(definition -> updateByRouteDefination(definition));
        return "success";
    }
}
